package com.ruoyi.web.controller.webapi;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basedata.domain.TerminalsDb;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.domain.TerminalsXbRGView;
import com.ruoyi.basedata.domain.vo.ConcentratorCommand;
import com.ruoyi.basedata.domain.vo.TerminalsXbProtocol;
import com.ruoyi.basedata.mapper.TerminalsXbMapper;
import com.ruoyi.basedata.service.IConcentratorService;
import com.ruoyi.basedata.service.ITerminalsDbService;
import com.ruoyi.basedata.service.ITerminalsXbService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.*;
import com.ruoyi.datastatistics.Agreement.GuoXinV1;
import com.ruoyi.datastatistics.domain.*;
import com.ruoyi.datastatistics.domain.recvdata.RecvData;
import com.ruoyi.datastatistics.domain.recvdata.RecvDataDb;
import com.ruoyi.datastatistics.domain.recvdata.RecvDataXb;
import com.ruoyi.datastatistics.service.*;
import com.ruoyi.web.convert.ConvertForm;
import com.ruoyi.web.entity.*;
import com.ruoyi.web.service.MeterApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 实时数据采集（小）Controller
 *
 * @author ruoyi
 * @date 2023-09-07
 */
@Slf4j
@RestController
@RequestMapping("/api")

public class WebApiController extends BaseController {

    @Value("${system-params.appKey}")
    public String appKey;
    //    @Value("${system-params.appSecret}")
    @Value("${system-params.appSecret}")
    private  String appSecret;
    @Value("${system-params.masterKey}")
    private  String masterKey;
    @Value("${system-params.productId}")
    private  String productId;
    @Resource
    private IDeGaocallBackService deGaocallBackService;
    @Autowired
    private IRealtimegatherdataXbService realtimegatherdataXbService;
    @Autowired
    private IRealtimegatherdataService realtimegatherdataService;
    @Autowired
    private IMeterHistoryDataService meterHistoryDataService;
    @Autowired
    private ITerminalsXbService terminalsXbService;
    @Autowired
    private ITerminalHistoryDataService terminalHistoryDataService;
    @Autowired
    private ITerminalsDbService terminalsDbService;
    @Autowired
    private IGuoXincallBackService guoXincallBackService;
    @Autowired
    private IConcentratorService concentratorService;
    @Resource
    private IGuoXincallDtuBackService guoXincallDtuBackService;
    @Resource
    private Environment env;
    @Autowired
    private MeterApiService meterApiService;
    @Autowired
    private RecvDataService recvDataService;

//    @GetMapping("/guoxindtuonMessage")
    @Anonymous
    @PostMapping("/guoxindtuonMessage")
    public void onGuoXinMessage(String message) {
        guoXincallBackService.callBackSubscribe(message,1);
        //guoXincallDtuBackService.callBackSubscribe(message);
    }

    /**
     * 获取小表档案数据+实时阀控状态、读数
     *
     * @param terminalsXb
     * @return
     */
    @GetMapping("/getterminalsXblist")
    public TableDataInfo getterminalsXblist(TerminalsXb terminalsXb) {
        if (StringUtils.isAllBlank(terminalsXb.getTenantId(),terminalsXb.getSheetsCode())){
            TableDataInfo info = new TableDataInfo();
            info.setCode(HttpStatus.ERROR);
            info.setMsg("tenantId和sheetsCode不能都为空，至少填一个");
            return info;
        }
        startPage();
        List<TerminalsXbRGView> list = terminalsXbService.selectTerminalsXbListAndRealtimegatherdata(terminalsXb);
        return getDataTable(list);
    }

    /**
     * 获取
     *
     * @param terminalsDb
     * @return
     */
    @GetMapping("/getterminalsDblist")
    public TableDataInfo getterminalsDblist(TerminalsDb terminalsDb) {
        startPage();
        List<TerminalsDb> list = terminalsDbService.selectTerminalsDbList(terminalsDb);
        return getDataTable(list);
    }

    /**
     * 查询实时数据采集（小）列表
     */
    /* @PreAuthorize("@ss.hasPermi('datastatistics:realtimegatherdataxb:list')")*/
    @GetMapping("/realtimegatherdataxblist")
    public TableDataInfo list(RealtimegatherdataXb realtimegatherdataXb) {
        startPage();
        List<RealtimegatherdataXb> list = realtimegatherdataXbService.selectRealtimegatherdataXbList2(realtimegatherdataXb);
        return getDataTable(list);
    }

    @GetMapping("/realtimegatherdatalist")
    public TableDataInfo list(Realtimegatherdata realtimegatherdata) {
        startPage();
        List<Realtimegatherdata> list = realtimegatherdataService.selectRealtimegatherdataList(realtimegatherdata);
        return getDataTable(list);
    }

    @GetMapping("/selectMeterHistoryDataList")
    public TableDataInfo list(MeterHistoryData meterHistoryData) throws ParseException {
        if (StringUtils.isAllBlank(meterHistoryData.getTenantId(), meterHistoryData.getSheetsCode())) {
            TableDataInfo info = new TableDataInfo();
            info.setCode(HttpStatus.ERROR);
            info.setMsg("tenantId和sheetsCode不能都为空，至少填一个");
            return info;
        } else if (meterHistoryData.getParams().get("beginReadDate") == null || meterHistoryData.getParams().get("endReadDate") == null) {
            TableDataInfo info = new TableDataInfo();
            info.setCode(HttpStatus.ERROR);
            info.setMsg("params[beginReadDate]和params[endReadDate]不能为空");
            return info;
        }

        startPage();
        List<MeterHistoryData> list = meterHistoryDataService.selectList(meterHistoryData);
        return getDataTable(list);
    }

    @GetMapping("/getTerminalHistoryDataList")
    public TableDataInfo list(TerminalsDb terminalsDb) throws ParseException {
        startPage();
        if (null == terminalsDb.getTerminalId() && null == terminalsDb.getLocationNb()) {
            return getDataTable(new ArrayList<TerminalHistoryData>());
        }
        String startTime = "";
        String endTime = "";
        if (null != terminalsDb.getParams() && terminalsDb.getParams().size() > 0) {
            startTime = terminalsDb.getParams().get("startTime") == null ? null : terminalsDb.getParams().get("startTime").toString();
            endTime = terminalsDb.getParams().get("endTime") == null ? null : terminalsDb.getParams().get("endTime").toString();
        }
        if (null == startTime || startTime.isEmpty() || null == endTime || endTime.isEmpty()) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            endTime = simpleDateFormat.format(new Date());
            startTime = DateUtil.getLastDayEndDate(endTime);
        }
        if (terminalsDb.getLocationNb() == null){
            List<TerminalsDb> list = terminalsDbService.list(new LambdaQueryWrapper<TerminalsDb>()
                    .eq(TerminalsDb::getTerminalId, terminalsDb.getTerminalId())
                    .eq(TerminalsDb::getDelFlag, 0)
                    .eq(TerminalsDb::getTerminalMark, 1));
            terminalsDb.setLocationNb(list.get(0).getLocationNb());
        }
        List<TerminalHistoryData> list = terminalHistoryDataService.getTerminalHistoryDataList(terminalsDb.getLocationNb(), startTime, endTime,null,null);
        return getDataTable(list);
    }

    @PostMapping("/updateRealtimegatherdataXbForWW")
    public AjaxResult updateRealtimegatherdataXbForWW(@RequestBody String realtimegatherdataXbForWW_) {
        log.info(realtimegatherdataXbForWW_);
        RealtimegatherdataXbForWW realtimegatherdataXbForWW = JSON.parseObject(realtimegatherdataXbForWW_, RealtimegatherdataXbForWW.class);
        TerminalsXb terminalsXb = new TerminalsXb();
        TerminalsXbProtocol terminalsXbProtocol = new TerminalsXbProtocol();
        if (realtimegatherdataXbForWW.getElecAddress().equals("")) {
            return error2("请完善设备信息");
        }
        //if(!imei.equals("")) terminalsXb.setIMEI(imei);
        if (!realtimegatherdataXbForWW.getElecAddress().equals("")) {
            terminalsXb.setCommunicateAddress(realtimegatherdataXbForWW.getElecAddress());
            List<TerminalsXbProtocol> list = terminalsXbService.selectTerminalsXbProtocolList(terminalsXb);
            if (list.size() > 0) {
                terminalsXbProtocol = list.get(0);
            } else {
                return error2("该设备不存在");
            }
            try {
                List<MeterHistoryData> list_ = new ArrayList<>();
                list_.add(ConvertForm.RealtimegatherdataXbFormWW(realtimegatherdataXbForWW, terminalsXbProtocol));
                guoXincallBackService.insertCallBack(list_, terminalsXbProtocol);
            } catch (Exception e) {
                return error2("异常");
            }
        }

        return success2("保存成功");
    }

    //01：开阀-----1
    //10：关阀----2
    @GetMapping("/createCommand")
    public AjaxResult createCommand(@RequestParam(value = "userID", required = false) String userID,
                                    @RequestParam(value = "isOpen", required = false) String isOpen
    ) {
        try {
            TerminalsXb terminalsXb = new TerminalsXb();
            if (userID.equals("")) {
                return error("请完善设备信息");
            }
            //if(!imei.equals("")) terminalsXb.setIMEI(imei);
            if (!userID.equals("")) terminalsXb.setUserId(userID);
            List<TerminalsXb> list = terminalsXbService.selectTerminalsXbList(terminalsXb);
            if (list.size() > 0) {
                terminalsXb = list.get(0);
            } else {
                return error("该表协议不存在");
            }

            /*TerminalsXbProtocol terminalsXbProtocol1 = new TerminalsXbProtocol();
            terminalsXbProtocol1.setCommunicateAddress(terminalsXb.getCommunicateAddress());
            terminalsXbProtocol1 = terminalsXbService.getcreateCommandParm(0, isOpen, terminalsXbProtocol1);
            //logger.info("terminalsXbProtocol1有值");
            if (terminalsXbProtocol1 == null){
                return error("该表协议不存在");
            }*/

            //解析命令
            byte[] valveControlData = GuoXinV1.getValveControlData(terminalsXb.getCommunicateAddress(), isOpen);
            String payload = GuoXinV1.bytesToHexString(valveControlData);
            //设置请求body
            JSONObject jsonObject = new JSONObject();
            Map<String, Object> content = new HashMap<>();
            content.put("dataType", 2);
            content.put("payload", payload);
            jsonObject.put("content", content);
            jsonObject.put("deviceId", terminalsXb.getDeviceId());
            jsonObject.put("ttl", 86400);
//            jsonObject.put("deviceId","49d898a3a6804635bcd6ac7b50b4ffa0");
            jsonObject.put("operator", "营收-api");
            jsonObject.put("productId", productId);
            //发送请求
            // logger.info("wodaozhe11111111111"+jsonObject);
            boolean flag = terminalsXbService.sendCreateCommand(jsonObject, appKey, appSecret, masterKey);
            if (!flag) {
                return error("发送创建命令请求时出错");
            }
            return success("命令已成功保存到AEP平台");
        } catch (Exception exception) {
            System.out.println(exception.getMessage());
            return error("系统异常");
        }
    }

    //阀门指令 0 开阀，1 关阀
    // @RequestParam(value = "no", required = false) String no,
    //                                                @RequestParam(value = "valveStatus", required = false
    @PostMapping("/valveControl")
    public AjaxResult createCommandvalveControl(@RequestBody String reslut
    ) {
        try {
            log.info("阀控命令下发：{}", reslut);
            JSONObject jo = JSONObject.parseObject(reslut);
            String no = jo.getString("no");
            Integer valveStatus = jo.getInteger("valveStatus");
            String supplierId = jo.getString("supplierId");
            TerminalsXb terminalsXb = new TerminalsXb();
            if (StringUtils.isBlank(no) || valveStatus == null) {
                return error("请完善设备信息");
            }
            terminalsXb.setTerminalId(no);
            if(supplierId != null){
                terminalsXb.setSupplierId(supplierId);
            }
            List<TerminalsXb> list = terminalsXbService.selectTerminalsXbList(terminalsXb);
            if (list.size() > 0) {
                terminalsXb = list.get(0);
            } else {
                return error("该表协议不存在");
            }

            /*TerminalsXbProtocol terminalsXbProtocol1 = new TerminalsXbProtocol();
            terminalsXbProtocol1.setCommunicateAddress(terminalsXb.getCommunicateAddress());
            terminalsXbProtocol1 = terminalsXbService.getcreateCommandParm(0, isOpen, terminalsXbProtocol1);
            //logger.info("terminalsXbProtocol1有值");
            if (terminalsXbProtocol1 == null){
                return error("该表协议不存在");
            }*/

            String isOpen = "";
            if (valveStatus == 1) {
                isOpen = "2";
            } else if (valveStatus == 0) {
                isOpen = "1";
            }
            //解析命令
            byte[] valveControlData = GuoXinV1.getValveControlData(terminalsXb.getCommunicateAddress(), isOpen);
            String payload = GuoXinV1.bytesToHexString(valveControlData);
            //设置请求body
            JSONObject jsonObject = new JSONObject();
            Map<String, Object> content = new HashMap<>(4);
            content.put("dataType", 2);
            content.put("payload", payload);
            jsonObject.put("content", content);
            jsonObject.put("deviceId", terminalsXb.getDeviceId());
            //德高AEP
            jsonObject.put("ttl", 86400);
            jsonObject.put("operator", "满洲里营收-api");
            jsonObject.put("productId", productId);
            //发送请求

            boolean flag = terminalsXbService.sendCreateCommand(jsonObject, appKey, appSecret, masterKey);
            if (!flag) {
                log.error("未能成功发送请求");
                return error("发送创建命令请求时出错");
            }
            log.info("命令已成功保存到AEP平台");
            return success("命令已成功保存到AEP平台");
        } catch (Exception exception) {
            log.error("系统异常",exception);
            return error("系统异常");
        }
    }

    @RepeatSubmit(interval = 3000, message = "请求过于频繁")
    @PostMapping("/valveControlPlatform")
    public AjaxResult valveControlPlatform(@RequestBody String result
    ) {
        try {
            log.info("阀控接口调用：{}", result);
            JSONObject jo = JSONObject.parseObject(result);
            String userCode = jo.getString("userCode");
            String terminalCode = jo.getString("terminalCode");
            Integer valveStatus = jo.getInteger("valveStatus");
            String supplierId = jo.getString("supplierId");
            String valveControl = jo.getString("commandType");//命令类型 开发阀命令：valveControl
            TerminalsXb terminalsXb = new TerminalsXb();
            //命令类型
            if (StringUtils.isBlank(valveControl)) {
                return error("commandType 命令类型不可为空！");
            }
            //不可同时为空
            if(StringUtils.isBlank(userCode)&& StringUtils.isBlank(terminalCode)){
                return error("用户编号和设备编号不可同时为空！");
            }
            //供应商必填
            if(!StringUtils.isBlank(supplierId)){
                terminalsXb.setSupplierId(supplierId);
            }else{
                return error("supplierId 不可为空！");
            }
            //开关阀状态
            if (valveStatus == null) {
                return error("valveStatus 不可为空！");
            }

            if (!StringUtils.isBlank(terminalCode)) {
                terminalsXb.setTerminalId(terminalCode);
            }

            if(!StringUtils.isBlank(userCode)){
                terminalsXb.setUserId(userCode);
            }


            List<TerminalsXb> list = terminalsXbService.selectTerminalsXbList(terminalsXb);
            if (list.size() > 0) {
                terminalsXb = list.get(0);
            } else {
                return error("该表协议不存在");
            }
            String isOpen = "";
            if (valveStatus == 1) {
                isOpen = "2";
            } else if (valveStatus == 0) {
                isOpen = "1";
            }
            //解析命令
            byte[] valveControlData = GuoXinV1.getValveControlData(terminalsXb.getCommunicateAddress(), isOpen);
            String payload = GuoXinV1.bytesToHexString(valveControlData);
            //设置请求body
            JSONObject jsonObject = new JSONObject();
            Map<String, Object> content = new HashMap<>(4);

            switch (terminalsXb.getSignPlatform()){
                case 1:
                    content.put("dataType", 2);
                    content.put("payload", payload);
                    jsonObject.put("content", content);
                    jsonObject.put("deviceId", terminalsXb.getDeviceId());
                    jsonObject.put("ttl", 86400);
                    jsonObject.put("operator", "满洲里营收-api");
                    jsonObject.put("productId", productId);
                    //发送请求
                    boolean flag = terminalsXbService.sendCreateCommand(jsonObject, appKey, appSecret, masterKey);
                    if (!flag) {
                        return error("发送创建命令请求时出错，设备编号："+ terminalsXb.getTerminalId());
                    }
                    // xbCommandLogsService.saveXbCommandLog(terminalsXbProtocol.getTerminalId(),isOpen.equals("1")?1:0,"命令已成功保存到AEP平台");
                    return success("命令已成功保存到AEP平台，设备编号："+ terminalsXb.getTerminalId());
                case 2:
                    List<TerminalsXbProtocol> terminalsXbProtocols = terminalsXbService.selectTerminalsXbProtocolList(terminalsXb);
                    terminalsXbProtocols.get(0).setImei(terminalsXb.getImei());
                    boolean flag2 = terminalsXbService.sendCreateCommandInOneNet(terminalsXbProtocols.get(0),payload);
                    if (!flag2) {
                        return error("发送创建命令请求时出错，设备编号："+ terminalsXb.getTerminalId());
                    }
                    return success("命令已成功保存到OneNet平台，设备编号： " + terminalsXb.getTerminalId());
                case 3:
                    String communicationType = DictUtils.getDictLabel("communication_type", terminalsXb.getCommunicationType());
                    String url = env.getProperty("netty-url." + communicationType + "." + "requestNetty");
                    String nettyBackBody = CommonHelper.getNettyBackBody(terminalsXb.getTerminalId(), valveControlData,url,communicationType);
                    return success("下发命令已保存，设备编号："+ terminalsXb.getTerminalId());
                default:
                    return error("default 设备平台未知,设备编号："+ terminalCode +",用户编号:"+ userCode+ "");
            }
        } catch (Exception exception) {
            log.error("系统异常",exception);
            return error("系统异常,入参：" + result);
        }
    }



    @GetMapping("/commandValueControl")
    public AjaxResult createCommandValueControl(@RequestParam(value = "terminalId", required = false) String terminalID,
                                                @RequestParam(value = "isOpen", required = false) String isOpen
    ){
        TerminalsXb terminalsXb = null;
        try {
            if (terminalID==null || isOpen==null){
                return error("请完善设备信息");
            }
            terminalsXb = terminalsXbService.selectTerminalsXbByTerminalID(terminalID);
            if (terminalsXb==null) return error("该表协议不存在");
            if (terminalsXb.getConcentratorId()==null) return error("该表未绑定集中器");
        }catch (Exception e){
            System.out.println(e.getMessage());
            return error("系统错误");
        }
        ConcentratorCommand concentratorCommand = ConcentratorCommand.builder()
                .commandType(4)
                .concentratorId(terminalsXb.getConcentratorAddress())
                .isOpen(isOpen)
                .meter(terminalsXb.getTerminalId())
                .supplierId(terminalsXb.getSupplierId())
                .build();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = concentratorService.sendCommand(concentratorCommand);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "系统异常，集中器命令下发失败");
        }
        return success(jsonObject);
    }


    @PostMapping("/parseGuoXinNb")
    public void parseGuoXinNb(@RequestBody Object obj){
        String msg = JSONObject.toJSONString(obj);

        //guoXincallBackService.callBackSubscribe(msg,1);
        deGaocallBackService.callBackNettySubscribe(msg);
    }

    @PostMapping("/test")
    public String test(@RequestBody String req) {
        log.info("接收到测试请求信息：{}", req);
        return "{\"code\": 0}";
    }


    //小表API，根据小表地址获取小表日、月冻结数据，数据源是101的demeter，该方法已弃用 2024-12-4 LX
    @GetMapping("/getDataListByMeterAdd")
    public String getDataListByMeterAdd(@RequestParam(value = "meterAdd")String meterAdd,
                                        @RequestParam(value = "startTime")String startTime,
                                        @RequestParam(value = "endTime")String endTime,
                                        @RequestParam(value = "dataType",defaultValue = "1")Integer dataType){
        try {
            String[] meterAdds = meterAdd.split(",");
            if(meterAdds.length<1){
                return JSONObject.toJSONString(Result.fail(HttpStatusEnum.BAD_REQUEST,"请输入正确的设备地址"));
            }
            Result res = meterApiService.getDataListByMeterAdd(meterAdds, startTime, endTime, dataType);
            return JSONObject.toJSONString(res);
        }catch (Exception e){
            return JSONObject.toJSONString(Result.fail(HttpStatusEnum.BAD_GATEWAY));
        }
    }

    //小表API，根据区域编号获取小表档案，数据源是101的demeter，该方法已弃用 2024-12-4 LX
    @GetMapping("/getMeteListByAreaCode")
    public String getMeteListByAreaCode(@RequestParam(value = "areaCode")String areaCode){
        List<Meter> meters = meterApiService.getMeteListByAreaCode(areaCode);
        return JSONObject.toJSONString(Result.success(meters));
    }

    /**
     *
     * 数据推送接口
     * 根据设备的档案信息和实时数据
     * @param terminalId
     * @param terminalName
     * @param signPlatform
     * @param locationNbs
     * @param loginUserId
     * @param sheetsCode
     * @param systemFlag
     * @param imei
     * @param tenantId
     * @return
     */
    @GetMapping("/getTerminalDblist")
    public TableDataInfo getTerminalDblist(@RequestParam(value = "terminalId", required = false) String terminalId,
                              @RequestParam(value = "terminalName", required = false) String terminalName,
                              @RequestParam(value = "signPlatform",required = false) String signPlatform,
                              @RequestParam(value = "locationNbs",required = false) String[] locationNbs,
                              @RequestParam(value = "loginUserId", required = false) Integer loginUserId,
                              @RequestParam(value = "sheetsCode", required = false) String sheetsCode,
                              @RequestParam(value = "systemFlag", required = false) Integer systemFlag,
                              @RequestParam(value = "imei", required = false) String imei,
                              @RequestParam(value = "tenantId", required = false) String tenantId) {
        if(StringUtils.isEmpty(terminalId) && StringUtils.isEmpty(locationNbs) && StringUtils.isEmpty(sheetsCode) && null == loginUserId && StringUtils.isEmpty(imei)){
            return getDataTableError(new ArrayList<TerminalHistoryData>(),"缺少必填项", HttpStatus.ERROR);
        }
        startPage();
        List<Realtimegatherdata> list = realtimegatherdataService.getRealtimegatherdataList(terminalId, terminalName,signPlatform,locationNbs,loginUserId,sheetsCode,systemFlag,imei,tenantId);
        return getDataTable(list);
    }


    /**
     * 数据推送接口
     * 根据设备历史数据
     * @param locationNb
     * @param startTime
     * @param endTime
     * @param maxTime
     * @param maxId
     * @return
     * @throws ParseException
     */
    @GetMapping("/getTerminalDbHistory")
    public TableDataInfo getTerminalDbHistory(
            @RequestParam(value = "locationNb", required = true) String locationNb,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "maxTime", required = false) String maxTime,
            @RequestParam(value = "maxId", required = false) Long maxId
    ) throws ParseException {
        if(StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime) && StringUtils.isEmpty(maxTime) && null == maxId ){
            return getDataTableError(new ArrayList<TerminalHistoryData>(),"缺少必填项", HttpStatus.ERROR);
        }
        startPage();
        List<TerminalHistoryData> list = terminalHistoryDataService.getTerminalHistoryDataList(locationNb, startTime, endTime,maxTime,maxId);
        return getDataTable(list);
    }

    @PostMapping("/recvData")
    public AjaxResult recvData(@Validated @RequestBody RecvData recvData, HttpServletRequest request) {
        String clientId = request.getHeader("Client-Id");
        int maxSize = 100;
        if (StringUtils.isBlank(clientId)) {
            return new AjaxResult(401, "请求未通过身份验证，需要提供有效的身份凭证");
        }
        if (CollectionUtils.isEmpty(recvData.getDatas()) || recvData.getDatas().size() > maxSize) {
            return new AjaxResult(400, "datas不能为空且最大不能超过" + maxSize);
        }
        recvData.setClientId(clientId);
        boolean success = recvDataService.saveRecvData(recvData);
        return success ? success() : error("未知错误，请联系接口提供方");
    }

    @PostMapping("/recvDataXb")
    public AjaxResult recvDataXb(@Validated @RequestBody RecvDataXb recvData, HttpServletRequest request) {
        String clientId = request.getHeader("Client-Id");
        int maxSize = 100;
        if (StringUtils.isBlank(clientId)) {
            return new AjaxResult(401, "请求未通过身份验证，需要提供有效的身份凭证");
        }
        // 实时数据类型
        String realtimeDataType = "1";
        // 历史数据类型
        String historyDataType = "2";
        recvData.setClientId(clientId);
        boolean success;
        if (historyDataType.equals(recvData.getDataType())) {
            if (CollectionUtils.isEmpty(recvData.getHistoryData()) || recvData.getHistoryData().size() > maxSize) {
                return new AjaxResult(400, "历史数据不能为空且最大条数不能超过" + maxSize);
            }
            success = recvDataService.saveRecvDataXb(recvData);
        } else if (realtimeDataType.equals(recvData.getDataType())) {
            if (recvData.getRealtimeData() == null) {
                return new AjaxResult(400, "实时数据不能为空");
            }
            success = recvDataService.saveRealtimeDataXb(recvData);
        } else {
            return new AjaxResult(400, "数据类型不正确");
        }
        return success ? success() : error("未知错误，请联系接口提供方");
    }

    @PostMapping("/recvDataDb")
    public AjaxResult recvDataDb(@Validated @RequestBody RecvDataDb recvData, HttpServletRequest request) {
        String clientId = request.getHeader("Client-Id");
        if (StringUtils.isBlank(clientId)) {
            return new AjaxResult(401, "请求未通过身份验证，需要提供有效的身份凭证");
        }
        recvData.setClientId(clientId);
        boolean success = recvDataService.saveRecvDataDb(recvData);
        return success ? success() : error("未知错误，请联系接口提供方");
    }


    /**
     *  能耗广场增加   满转状态  版本
     *  水表专用
     * @param recvDataList
     * @param request
     * @return
     */
    @PostMapping("/recvDataXbBatch")
    public AjaxResult recvDataXbBatch(@Validated @RequestBody List<RecvDataXb> recvDataList, HttpServletRequest request) {
        System.out.println("=========================================into");
        String clientId = request.getHeader("Client-Id");
        int maxSize = 100;
        int maxSizeList = 800;
        if (StringUtils.isBlank(clientId)) {
            return new AjaxResult(401, "请求未通过身份验证，需要提供有效的身份凭证");
        }
        boolean success = true ;
        if(CollectionUtils.isEmpty(recvDataList) ||  recvDataList.size() > maxSizeList) {
            return new AjaxResult(400, "历史数据不能为空且最大条数不能超过" + maxSizeList);
        }
        List<String>  deviceNumberList =   recvDataList.stream().map(recvData -> {return
                recvData.getDeviceNumber();}).collect(Collectors.toList());

        List<TerminalsXb>  terminalsXbList = terminalsXbService.list();
        if(CollectionUtils.isEmpty(terminalsXbList)){
            return new AjaxResult(400, "设备不存在!");
        }
        success = recvDataService.saveRecvDataXbBatch(recvDataList);
        return success ? success() : error("未知错误，请联系接口提供方");
    }

    /**
     * 能耗广场 未 增加满转状态版本
     * @param recvDataList
     * @param request
     * @return
     */
    @PostMapping("/recvDataXbBatchCopy")
    public AjaxResult recvDataXbBatchCopy(@Validated @RequestBody List<RecvDataXb> recvDataList, HttpServletRequest request) {
        System.out.println("=========================================into");
        String clientId = request.getHeader("Client-Id");
        int maxSize = 100;
        int maxSizeList = 800;
        if (StringUtils.isBlank(clientId)) {
            return new AjaxResult(401, "请求未通过身份验证，需要提供有效的身份凭证");
        }
        // 实时数据类型
        // String realtimeDataType = "1";
        // // 历史数据类型
        // String historyDataType = "2";
        // recvData.setClientId(clientId);
        boolean success = true ;
        if(CollectionUtils.isEmpty(recvDataList) ||  recvDataList.size() > maxSizeList) {
            return new AjaxResult(400, "历史数据不能为空且最大条数不能超过" + maxSizeList);
        }
        List<String>  deviceNumberList =   recvDataList.stream().map(recvData -> {return
                recvData.getDeviceNumber();}).collect(Collectors.toList());

        List<TerminalsXb>  terminalsXbList = terminalsXbService.list();
        if(CollectionUtils.isEmpty(terminalsXbList)){
            return new AjaxResult(400, "设备不存在!");
        }
        // List<String>  terminalIdListExist =   terminalsXbList.stream().map(e -> e.getTerminalId()).collect(Collectors.toList());
        // List<String>  terminalIdListNotExist  =  deviceNumberList.stream().filter(e->!terminalIdListExist.contains(e)).collect(Collectors.toList());
        // if(CollectionUtils.isNotEmpty(terminalIdListNotExist)){
        //     return new AjaxResult(400, "以下设备号不存在：" + String.join(" , " , terminalIdListNotExist));
        // }
        success = recvDataService.saveRecvDataXbBatchCopy(recvDataList);
        return success ? success() : error("未知错误，请联系接口提供方");
    }




}
